package com.zz.utils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.commons.codec.digest.DigestUtils;
import org.joda.time.DateTime;
import org.springframework.web.multipart.MultipartFile;

public class FileHelper {

  private static FileHelper instance = new FileHelper();
  public static String CONTEXT_DISK_FILE_PATH;
  private static final String UPLOAD_PATH = "/upload";

  private FileHelper() {
  }

  public static void initPath() {
    // CONTEXT_DISK_FILE_PATH = CONTEXT_DISK_FILE_PATH + UPLOAD_PATH;

    FILE_TYPE[] types = FILE_TYPE.values();
    for (FILE_TYPE type : types) {
      String path = CONTEXT_DISK_FILE_PATH + UPLOAD_PATH + type.getPath();

      File directory = new File(path);
      if (directory.isFile()) {
        directory.delete();
      }
      if (!directory.exists()) {
        directory.mkdirs();
      }
    }
  }

  public static String saveFile(MultipartFile file, FILE_TYPE filetype) {
    if (file == null || file.getSize() == 0) {
      return null;
    }

    FileMeta meta = fileMeta(filetype);
    try {
      saveFileToDisk(meta.getDiskPath(), file);
      return meta.getWebPath();
    } catch (Exception e) {
      return null;
    }
  }

  private static FileMeta fileMeta(FILE_TYPE filetype) {
    FileMeta meta = instance.new FileMeta();

    String path = filetype.getPath();

    String fileName = DigestUtils.md5Hex(DateTime.now().toString()) + ".png";
    path = path + fileName;

    meta.setName(fileName);
    meta.setDiskPath(CONTEXT_DISK_FILE_PATH + UPLOAD_PATH + path);
    meta.setWebPath(UPLOAD_PATH + path);

    return meta;
  }

  private static void saveFileToDisk(String filePath, MultipartFile file) throws Exception {
    InputStream in = null;
    OutputStream out = null;
    try {
      in = file.getInputStream();
      out = new FileOutputStream(filePath);
      int read = 0;
      byte[] buffer = new byte[8192];

      while ((read = in.read(buffer, 0, 8192)) != -1) {
        out.write(buffer, 0, read);
      }
      out.close();
      in.close();
    } catch (Exception e) {
      if (in != null) {
        in.close();
      }
      if (out != null) {
        out.close();
      }
      e.printStackTrace();
      throw e;
    }
  }

  @SuppressWarnings("unused")
  private class FileMeta {

    private String diskPath;
    private String name;
    private String webPath;

    public String getDiskPath() {
      return diskPath;
    }

    public void setDiskPath(String diskPath) {
      this.diskPath = diskPath;
    }

    public String getName() {
      return name;
    }

    public void setName(String name) {
      this.name = name;
    }

    public String getWebPath() {
      return webPath;
    }

    public void setWebPath(String webPath) {
      this.webPath = webPath;
    }

  }

}